package com.yao.code;

import com.yao.tool.TreeNode;

/**
 * @author yaoquanwei
 * @date 2021/8/14 15:02
 */
public class Code210814 {

    /**
     * 剑指offer 26.树的子结构
     *
     * @param A
     * @param B
     * @return
     */
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if (A == null || B == null) {
            return false;
        }
        return isSame(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }

    /**
     * 判断两棵树是否相等
     *
     * @param A
     * @param B
     * @return
     */
    public boolean isSame(TreeNode A, TreeNode B) {
        if (B == null) {
            return true;
        }
        if (A == null) {
            return false;
        }
        return A.val == B.val && isSame(A.left, B.left) && isSame(A.right, B.right);
    }

    /**
     * 剑指offer 27.二叉树的镜像
     *
     * @param root
     * @return
     */
    public static TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        root.left = mirrorTree(root.left);
        root.right = mirrorTree(root.right);
        TreeNode tem = root.left;
        root.left = root.right;
        root.right = tem;
        return root;
    }

    /**
     * 剑指offer 28.对称的二叉树
     *
     * @param root
     * @return
     */
    public static boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSameValue(root.left, root.right);
    }

    public static boolean isSameValue(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) {
            return true;
        } else if (root1 == null || root2 != null) {
            return false;
        } else if (root1.val != root2.val) {
            return false;
        } else {
            return isSameValue(root1.left, root2.right) && isSameValue(root1.right, root2.left);
        }
    }

}
